package com.demo.controller;

import com.demo.common.Result;
import com.demo.pojo.entity.Teacher;
import com.demo.service.TeacherService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;

import jakarta.validation.Valid;

/**
 * 教师个人中心控制器
 * 提供教师个人信息的查询和更新功能
 * 
 * @author 潘建冰
 * @date 2025/1/27
 */
@RestController
@RequestMapping("/teacher/personal")
@Validated
public class TeacherPersonalController {

    private final TeacherService teacherService;

    public TeacherPersonalController(TeacherService teacherService) {
        this.teacherService = teacherService;
    }

    /**
     * 根据教师ID获取个人信息
     * @param teacherId 教师ID
     * @return 教师个人信息
     */
    @GetMapping("/info")
    public Result<Teacher> getPersonalInfo(@RequestParam Long teacherId) {
        Teacher teacher = teacherService.selectById(teacherId.intValue());
        return Result.success(teacher);
    }

    /**
     * 根据工号获取个人信息
     * @param teNo 教师工号
     * @return 教师个人信息
     */
    @GetMapping("/info/byNo")
    public Result<Teacher> getPersonalInfoByNo(@RequestParam Long teNo) {
        Teacher teacher = teacherService.getByTeNo(teNo);
        if (teacher == null) {
            return Result.error("未找到该教师信息");
        }
        return Result.success(teacher);
    }

    /**
     * 更新教师个人信息
     * @param teacher 教师信息
     * @return 更新结果
     */
    @PutMapping("/update")
    public Result<Void> updatePersonalInfo(@Valid @RequestBody Teacher teacher) {
        teacherService.updateTeacher(teacher);
        return Result.success();
    }

    /**
     * 更新教师基本信息（部分字段）
     * @param teacher 教师信息
     * @return 更新结果
     */
    @PatchMapping("/update/basic")
    public Result<Void> updateBasicInfo(@RequestBody Teacher teacher) {
        teacherService.updateBasicInfo(teacher);
        return Result.success();
    }

    /**
     * 获取当前教师信息（支持通过teacherId或teNo查询）
     * 优先使用teacherId；若未提供则尝试使用teNo
     */
    @GetMapping("/current")
    public Result<Teacher> getCurrent(@RequestParam(required = false) Long teacherId,
                                      @RequestParam(required = false) Long teNo) {
        Teacher teacher = null;
        if (teacherId != null) {
            teacher = teacherService.selectById(teacherId.intValue());
        } else if (teNo != null) {
            teacher = teacherService.getByTeNo(teNo);
        } else {
            return Result.error("缺少teacherId或teNo参数");
        }
        return Result.success(teacher);
    }

    /**
     * 教师登录：根据姓名+手机号，返回教师完整信息
     */
    @PostMapping("/loginByNamePhone")
    public Result<Teacher> loginByNamePhone(@RequestParam String teName,
                                            @RequestParam String tePhone) {
        Teacher teacher = teacherService.getByNameAndPhone(teName, tePhone);
        return Result.success(teacher);
    }
}

